//
//  SecondViewController.m
//  PrayerTimes
//
//  Created by Igor Karpenko on 6/8/13.
//  Copyright (c) 2013 Igor Karpenko. All rights reserved.
//

#import "JBTabBarController.h"
#import "PrayerTimesTableViewCell.h"
#import "ChangeCityViewController.h"
#import <AVFoundation/AVFoundation.h>

#import "PrayerTimesViewController.h"

@interface PrayerTimesViewController ()

@property (nonatomic, retain) AVAudioPlayer *player;

@end


static NSString *timeTableReuseIdentifier = @"timeTableReuseIdentifier";

@implementation PrayerTimesViewController

#pragma mark - Instance initialization

-(id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (!self) {
		return nil;
    }

	self.title = NSLocalizedString(@"Prayer times", nil);
	self.tabBarItem.image = [UIImage imageNamed:@"gnr_prayerIcon"];
	self.tabBarItem.selectedImage = [UIImage imageNamed:@"gnr_prayerIcon_active"];
	
	timesManager = [PrayerTimesManager sharedInstance];
	dataProvider = [DataProvider sharedInstance];
	
	return self;
}


#pragma mark - Memory managment

-(void) dealloc {
	if (_player) {
		[_player release];
	}
	[_overlayImage release];
	[_englishButton release];
	[_arabButton release];
	[_locationLabel release];
	[_dateLabel release];
	[_alarmButton release];
	[_changeCityButton release];
	[_tableView release];
	[_items release];
	[_prayerTime release];
	
	[_fajr release];
	[_sunrise release];
	[_dhuhr release];
	[_asr release];
	[_maghrib release];
	[_isha release];
	
    [super dealloc];
}


#pragma mark - Interface methods

-(void) viewDidLoad {
    [super viewDidLoad];
	
	_overlayImage.image = [_overlayImage.image resizableImageWithCapInsets:UIEdgeInsetsMake(230.0f, 0.0f, 20.0f, 0.0f)];
	_alarmButton.alpha = ([dataProvider.alarmOn boolValue] ? 1.0f : 0.5f);
	
	[self reloadPrayerTimes];
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDataChanged)
												 name:PrayerTimesManagerDidSaveUserData
											   object:nil];
}


-(void) viewDidUnload {
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	
    [self setOverlayImage:nil];
	[self setEnglishButton:nil];
	[self setArabButton:nil];
	[self setLocationLabel:nil];
	[self setDateLabel:nil];
	[self setAlarmButton:nil];
	[self setChangeCityButton:nil];
	[self setTableView:nil];
	
    [super viewDidUnload];
}


-(void) viewWillAppear:(BOOL)animated {
	_locationLabel.text = [NSString stringWithFormat:@"%@, %@", dataProvider.currentCountry, dataProvider.currentCity];
	NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
	[formatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]] ;
	formatter.dateFormat = @"dd MMM yyyy";
	_dateLabel.text = [formatter stringFromDate:[NSDate date]];

	
	if (dataProvider.currentCountry != nil) {
		[timesManager checkTimeTableForNextMonth];
	}
	
	if ([dataProvider.language isEqualToString:@"English"]) {
		_englishButton.enabled = NO;
		_arabButton.enabled = YES;
	} else {
		_englishButton.enabled = YES;
		_arabButton.enabled = NO;
	}
	
	[self checkTimeSelection];
	[self changeLanguage];
}


-(void) viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
	
	if (_timer) {
		[_timer invalidate];
		_timer = nil;
	}
}


-(void) viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	
	[self checkNotifications];
}


-(void) playPrayerSound {
	[self playSoundNamed:@"Azaan.mp3"];
}


#pragma mark - Action methods

-(IBAction) englishButtonTapped:(id)sender {
	_englishButton.enabled = NO;
	_arabButton.enabled = YES;
	LocalizationSetLanguage(@"English");
	dataProvider.language = @"English";
	[self changeLanguage];
}


-(IBAction) arabButtonTapped:(id)sender {
	_arabButton.enabled = NO;
	_englishButton.enabled = YES;
	LocalizationSetLanguage(@"Arabic");
	dataProvider.language = @"Arabic";
	[self changeLanguage];
}


-(IBAction) alarmButtonTapped:(id)sender {
	BOOL alarmStateOn = [dataProvider.alarmOn boolValue];

	[[UIApplication sharedApplication] cancelAllLocalNotifications];
	if (alarmStateOn) {
		_alarmButton.alpha = 0.5f;
		dataProvider.alarmOn = [NSNumber numberWithBool:NO];
		dataProvider.notificationUpdateDay = [NSNumber numberWithInt:100];
	} else {
		HUD = [[MBProgressHUD alloc] initWithView:self.view];
		[self.view addSubview:HUD];
		
		HUD.delegate = self;
		HUD.labelText = @"Please wait...";
		
		[HUD showWhileExecuting:@selector(setNotifications) onTarget:self withObject:nil animated:YES];

		_alarmButton.alpha = 1.0f;
	}
}


-(IBAction) changeCityButtonTapped:(id)sender {
	ChangeCityViewController *controller = [[ChangeCityViewController alloc] initWithNibName:@"ChangeCityViewController"
																					  bundle:nil];
	UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
	[rootViewController presentViewController:controller
									  animated:YES
									completion:nil];
	[controller release];
}


#pragma mark - Private methods 

-(void) changeLanguage {
	((PrayerTimesTableViewCell *)_tableView.visibleCells[0]).titleLabel.text = AMLocalizedString(@"fajr", nil);
	((PrayerTimesTableViewCell *)_tableView.visibleCells[1]).titleLabel.text = AMLocalizedString(@"sunrise", nil);
	((PrayerTimesTableViewCell *)_tableView.visibleCells[2]).titleLabel.text = AMLocalizedString(@"dhuhr", nil);
	((PrayerTimesTableViewCell *)_tableView.visibleCells[3]).titleLabel.text = AMLocalizedString(@"asr", nil);
	((PrayerTimesTableViewCell *)_tableView.visibleCells[4]).titleLabel.text = AMLocalizedString(@"maghrib", nil);
	((PrayerTimesTableViewCell *)_tableView.visibleCells[5]).titleLabel.text = AMLocalizedString(@"isha", nil);
	[_changeCityButton setTitle:AMLocalizedString(@"changeCity", nil) forState:UIControlStateNormal];
}


-(void) reloadPrayerTimes {
	if (dataProvider.currentCountry == nil) {
		return;
	}
	
	_prayerTime = [timesManager getPrayerTimeForToday];
	
	NSString *am = @" AM";
	NSString *pm = @" PM";
	
	self.fajr = [_prayerTime.$_fajr stringByAppendingString:am];
	self.sunrise = [_prayerTime.$_sunrise stringByAppendingString:am];
	int dhuhrHour = [[[_prayerTime.$_dhuhr componentsSeparatedByString:@":"] objectAtIndex:0] integerValue];
	self.dhuhr = [_prayerTime.$_dhuhr stringByAppendingString:(dhuhrHour == 12 || dhuhrHour <= 5) ? pm : am];
	self.asr = [_prayerTime.$_asr stringByAppendingString:pm];
	self.maghrib = [_prayerTime.$_maghrib stringByAppendingString:pm];
	self.isha = [_prayerTime.$_isha stringByAppendingString:pm];
	
	[_tableView reloadData];
}


-(void) checkTimeSelection {
	if (dataProvider.currentCountry == nil) {
		return;
	}
	
	if (!_timer) {
		_timer = [NSTimer scheduledTimerWithTimeInterval:60.0f
												 target:self
											   selector:@selector(checkTimeSelection)
											   userInfo:nil
												repeats:YES];
	}
	
	NSDate *currentDate = [NSDate date];
	int newIndex = -1;
	
	if ([currentDate compare:[self parseDateFromString:_fajr]] == NSOrderedAscending) {
		newIndex = 0;
	} else if ([currentDate compare:[self parseDateFromString:_sunrise]] == NSOrderedAscending) {
		newIndex = 1;
	} else if ([currentDate compare:[self parseDateFromString:_dhuhr]] == NSOrderedAscending) {
		newIndex = 2;
	} else if ([currentDate compare:[self parseDateFromString:_asr]] == NSOrderedAscending) {
		newIndex = 3;
	} else if ([currentDate compare:[self parseDateFromString:_maghrib]] == NSOrderedAscending) {
		newIndex = 4;
	} else {
		newIndex = 5;
	}
	
	if (newIndex == currentIndex) {
		return;
	}
	currentIndex = newIndex;
	
	for (int i = 0; i < 6; i++) {

		((PrayerTimesTableViewCell *)_tableView.visibleCells[i]).selected = NO;
	}
	
	((PrayerTimesTableViewCell *)_tableView.visibleCells[currentIndex]).selected = YES;
}


-(void) checkNotifications {
	if (dataProvider.currentCountry == nil) {
		return;
	}
	
	NSDateComponents *currentDateComponents = [[NSCalendar currentCalendar] components:NSDayCalendarUnit
																			  fromDate:[NSDate date]];
	int diference = abs([dataProvider.notificationUpdateDay integerValue] - currentDateComponents.day);
	if ([dataProvider.alarmOn boolValue] && diference > 9) {
		[[UIApplication sharedApplication] cancelAllLocalNotifications];
		[self setNotifications];
	}
	
}


-(NSDate *) parseDateFromString:(NSString *)dateString {
	NSDate *currentDate = [NSDate date];
	
	NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
	[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];
	[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
	[dateFormatter setDateFormat:@"MM/dd/yyyy"];
	NSString *currentDateString = [dateFormatter stringFromDate:currentDate];
	
	NSString *parseString = [currentDateString stringByAppendingFormat:@" %@", dateString];
	[dateFormatter setDateFormat:@"MM/dd/yyyy h:mm a"];
	return  [dateFormatter dateFromString:parseString];
}


-(void) scheduleNotificationWithDate:(NSDate *)date title:(NSString *)title {
	NSDate *currentDate = [NSDate date];
	if ([currentDate compare:date] == NSOrderedDescending) {
		return;
	}
	
    UILocalNotification *localNotification = [[[UILocalNotification alloc] init] autorelease];
    localNotification.fireDate = date;
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
	
    localNotification.alertBody = title;
    localNotification.alertAction = NSLocalizedString(@"View Details", nil);
	
    localNotification.soundName = @"alert.caf";
    localNotification.applicationIconBadgeNumber = 1;
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}


-(void) setNotifications {
	NSArray *alerts = [timesManager getTimesForNotification];
	for (NSDictionary *dictionary in alerts) {
		[self scheduleNotificationWithDate:[dictionary valueForKey:NOTIFICATION_DATE_KEY]
									 title:[dictionary valueForKey:NOTIFICATION_TITLE_KEY]];
	}

	NSDateComponents *currentDateComponents = [[NSCalendar currentCalendar] components:NSDayCalendarUnit
																			  fromDate:[NSDate date]];
	dataProvider.alarmOn = [NSNumber numberWithBool:YES];
	dataProvider.notificationUpdateDay = @(currentDateComponents.day);
}


-(BOOL) playSoundNamed:(NSString*)name {
	NSError *error;
	NSBundle* bundle = [NSBundle mainBundle];
	NSString* bundleDirectory = (NSString*)[bundle bundlePath];
	NSURL *url = [NSURL fileURLWithPath:[bundleDirectory stringByAppendingPathComponent:name]];
	
	_player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
	
	BOOL success = YES;
	if (_player == nil) {
        success = NO;
    } else {
		[_player prepareToPlay];
        success = [_player play];
    }
    return success;
}


#pragma mark - Notification observers

-(void) userDataChanged {
	currentIndex = -1;
	[self reloadPrayerTimes];
	[self checkTimeSelection];
}


#pragma mark - Data source methods

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return 6;
}


-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	PrayerTimesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:timeTableReuseIdentifier];
	
	if (!cell) {
		cell = [[[NSBundle mainBundle] loadNibNamed:@"PrayerTimesTableViewCell" owner:nil options:nil] lastObject];
	}
	
	switch (indexPath.row) {
		case 0:
			cell.titleLabel.text = @"Fajr";
			cell.timeLabel.text = _fajr;
			break;
		case 1:
			cell.titleLabel.text = @"Sunrise";
			cell.timeLabel.text = _sunrise;
			break;
		case 2:
			cell.titleLabel.text = @"Dhuhr";
			cell.timeLabel.text = _dhuhr;
			break;
		case 3:
			cell.titleLabel.text = @"Asr";
			cell.timeLabel.text = _asr;
			break;
		case 4:
			cell.titleLabel.text = @"Maghrib";
			cell.timeLabel.text = _maghrib;
			break;
		case 5:
			cell.titleLabel.text = @"Isha";
			cell.timeLabel.text = _isha;
			break;
		default:
			$l("unknown table row");
			break;
	}
	
	return cell;
}


#pragma mark MBProgressHUDDelegate methods

-(void) hudWasHidden:(MBProgressHUD *)hud {
	// Remove HUD from screen when the HUD was hidded
	[HUD removeFromSuperview];
	[HUD release];
	HUD = nil;
}

@end
